package com.yiyuzi.wiki.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

/**
 * 拦截器
 *
 * @author yiyuzi
 * @date 2021/5/8 17:05
 */

@Component
public class WikiInterceptorAdapter implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(WikiInterceptorAdapter.class);

    private ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        LogRecord logRecord = method.getAnnotation(LogRecord.class);
        if (logRecord != null) {
            threadLocal.set(System.currentTimeMillis());
        }

        LOGGER.info("================================== preHandle：{} ===========================================", method.getName());

        // 登录拦截
//        StringBuffer url = request.getRequestURL();
//        for (int i = 0; i < 3; i++)
//            url.delete(0, url.indexOf("/") + 1);
//        LOGGER.info("{}", url);
        // 放行的url
//        Pattern pattern = Pattern.compile("((.*.html)|(.*.js)|(.*.css)|(.*.ico)|(.*login))");
//        if (pattern.matcher(url.toString()).find()) {
//            return true;
//        }
        // TODO 修改跨域范围
//        response.setHeader("Access-Control-Allow-Origin", "https://49.234.88.43, https://localhost:8080, https://yiyuzi.top");
        response.setHeader("Access-Control-Allow-Origin", "*");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        LogRecord logRecord = method.getAnnotation(LogRecord.class);
        if (logRecord != null) {
            long startTime = threadLocal.get();
            long endTime = System.currentTimeMillis();
            long costTime = endTime - startTime;

            String requestUri = request.getRequestURI();
            String methodName = method.getDeclaringClass().getName() + "." + method.getName();
            String methodDesc = logRecord.methodDesc();

            LOGGER.info("================================== postHandle：{} {} ms  ===========================================", methodName, costTime);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.info("================================== afterCompletion ===========================================");
    }
}
